export interface PasswordOptions {
    length: number;
    includeUppercase: boolean;
    includeLowercase: boolean;
    includeNumbers: boolean;
    includeSymbols: boolean;
    excludeSimilar: boolean;
    excludeAmbiguous: boolean;
    customSymbols: string;
}

export interface PasswordStrength {
    score: number; // 0-100
    level: 'weak' | 'medium' | 'strong' | 'very-strong';
    feedback: string[];
}

// 字符集定义
const CHARACTER_SETS = {
    uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    lowercase: 'abcdefghijklmnopqrstuvwxyz',
    numbers: '0123456789',
    symbols: '!@#$%^&*()_+-=[]{}|;:,.<>?',
    similar: 'il1Lo0O',
    ambiguous: '{}[]()/\\\'"`~,;:.<>'
};

// 预设的特殊字符组
export const PRESET_SYMBOL_GROUPS = {
    basic: '!@#$%^&*',
    brackets: '()[]{}<>',
    punctuation: '.,;:?!',
    math: '+-=*/',
    currency: '$€£¥¢',
    arrows: '<>^v',
    misc: '~`|\\/_'
};

// 生成随机密码
export function generatePassword(options: PasswordOptions): string {
    let charset = '';

    // 构建字符集
    if (options.includeUppercase) charset += CHARACTER_SETS.uppercase;
    if (options.includeLowercase) charset += CHARACTER_SETS.lowercase;
    if (options.includeNumbers) charset += CHARACTER_SETS.numbers;
    if (options.includeSymbols) {
        // 使用自定义特殊字符，如果没有则使用默认字符集
        const symbolsToUse = options.customSymbols.trim() || CHARACTER_SETS.symbols;
        charset += symbolsToUse;
    }

    // 排除相似字符
    if (options.excludeSimilar) {
        charset = charset.split('').filter(char => !CHARACTER_SETS.similar.includes(char)).join('');
    }

    // 排除易混淆字符
    if (options.excludeAmbiguous) {
        charset = charset.split('').filter(char => !CHARACTER_SETS.ambiguous.includes(char)).join('');
    }

    // 确保至少有一种字符类型
    if (charset.length === 0) {
        charset = CHARACTER_SETS.lowercase + CHARACTER_SETS.numbers;
    }

    // 生成密码
    let password = '';
    const array = new Uint8Array(options.length);
    crypto.getRandomValues(array);

    for (let i = 0; i < options.length; i++) {
        password += charset[array[i] % charset.length];
    }

    // 确保密码包含所有选中的字符类型
    password = ensureCharacterTypes(password, options);

    return password;
}

// 确保密码包含所有选中的字符类型
function ensureCharacterTypes(password: string, options: PasswordOptions): string {
    const chars = password.split('');
    let hasUppercase = false;
    let hasLowercase = false;
    let hasNumbers = false;
    let hasSymbols = false;

    // 检查当前密码包含的字符类型
    for (const char of chars) {
        if (CHARACTER_SETS.uppercase.includes(char)) hasUppercase = true;
        if (CHARACTER_SETS.lowercase.includes(char)) hasLowercase = true;
        if (CHARACTER_SETS.numbers.includes(char)) hasNumbers = true;
        if (CHARACTER_SETS.symbols.includes(char)) hasSymbols = true;
    }

    // 如果缺少某种字符类型，随机替换一个字符
    if (options.includeUppercase && !hasUppercase) {
        const randomIndex = Math.floor(Math.random() * chars.length);
        chars[randomIndex] = CHARACTER_SETS.uppercase[Math.floor(Math.random() * CHARACTER_SETS.uppercase.length)];
    }

    if (options.includeLowercase && !hasLowercase) {
        const randomIndex = Math.floor(Math.random() * chars.length);
        chars[randomIndex] = CHARACTER_SETS.lowercase[Math.floor(Math.random() * CHARACTER_SETS.lowercase.length)];
    }

    if (options.includeNumbers && !hasNumbers) {
        const randomIndex = Math.floor(Math.random() * chars.length);
        chars[randomIndex] = CHARACTER_SETS.numbers[Math.floor(Math.random() * CHARACTER_SETS.numbers.length)];
    }

    if (options.includeSymbols && !hasSymbols) {
        const randomIndex = Math.floor(Math.random() * chars.length);
        const symbolsToUse = options.customSymbols.trim() || CHARACTER_SETS.symbols;
        chars[randomIndex] = symbolsToUse[Math.floor(Math.random() * symbolsToUse.length)];
    }

    return chars.join('');
}

// 评估密码强度
export function evaluatePasswordStrength(password: string, customSymbols: string = ''): PasswordStrength {
    let score = 0;
    const feedback: string[] = [];

    // 长度评分
    if (password.length < 8) {
        feedback.push('密码长度至少8位');
    } else if (password.length >= 12) {
        score += 25;
    } else {
        score += password.length * 2;
    }

    // 字符类型评分
    let hasUppercase = false;
    let hasLowercase = false;
    let hasNumbers = false;
    let hasSymbols = false;

    for (const char of password) {
        if (CHARACTER_SETS.uppercase.includes(char)) hasUppercase = true;
        if (CHARACTER_SETS.lowercase.includes(char)) hasLowercase = true;
        if (CHARACTER_SETS.numbers.includes(char)) hasNumbers = true;
        // 检查是否包含特殊字符（包括自定义的）
        if (CHARACTER_SETS.symbols.includes(char) || (customSymbols && customSymbols.includes(char))) hasSymbols = true;
    }

    if (hasUppercase) score += 10;
    if (hasLowercase) score += 10;
    if (hasNumbers) score += 10;
    if (hasSymbols) score += 15;

    // 多样性评分
    const uniqueChars = new Set(password).size;
    score += Math.min(uniqueChars * 2, 20);

    // 反馈信息
    if (!hasUppercase) feedback.push('建议包含大写字母');
    if (!hasLowercase) feedback.push('建议包含小写字母');
    if (!hasNumbers) feedback.push('建议包含数字');
    if (!hasSymbols) feedback.push('建议包含特殊字符');

    if (uniqueChars < password.length * 0.6) {
        feedback.push('建议增加字符多样性');
    }

    // 确定强度等级
    let level: PasswordStrength['level'];
    if (score < 30) {
        level = 'weak';
    } else if (score < 60) {
        level = 'medium';
    } else if (score < 80) {
        level = 'strong';
    } else {
        level = 'very-strong';
    }

    return {
        score: Math.min(score, 100),
        level,
        feedback
    };
}

// 生成密码建议
export function generatePasswordSuggestions(): string[] {
    const suggestions = [
        '使用至少12位字符',
        '包含大小写字母、数字和特殊字符',
        '避免使用个人信息（生日、姓名等）',
        '避免使用常见密码模式',
        '为不同账户使用不同密码',
        '定期更换密码',
        '使用密码管理器存储密码'
    ];

    return suggestions;
} 